<template>  
  <AppCover section="profile" :bgURL="coverURL" :bgPrURL="coverPrURL" />
  <div id="UserProfile">    
    <div class="content">
      <div class="userOriginal">
        <p class="titleTip">我的信息</p>
        <div 
          class="img"
          :style="{
            backgroundImage: `url(${baseURL}${userInfo.avatar})`
          }"
        ></div>
        <p class="nickName">{{ userInfo.user }}</p>
        <p class="userRegDate">
          <span>注册日期：</span>
          {{ formatDate(userInfo.regDate) }}
        </p>
      </div>
      <div class="modifyInfo">
        <p class="titleTip modifyTitle">修改信息</p>
        <el-tabs :tab-position="tabPosition">
          <el-tab-pane label="修改昵称">
            <div class="modifyName">
              <el-form :model="nameForm" :rules="rules" ref="nameForm">
                <el-form-item>
                  <!-- <el-input :placeholder="userInfo.user" :disabled="true"> -->
                  <el-input :placeholder="oldName" :disabled="true">
                    <template #prepend>原昵称：</template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="newName">
                  <el-input 
                    placeholder="请输入内容" 
                    v-model="nameForm.newName" 
                    clearable
                    @keyup.enter="saveNameHandler"
                  >
                    <template #prepend>新昵称：</template>
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <el-button plain @click="saveNameHandler">保存</el-button>
          </el-tab-pane>          
          <el-tab-pane label="修改密码">
            <div class="modifyPW">
              <el-form :model="passForm" :rules="rules" ref="passForm">
                <el-form-item prop="oldpw">
                  <el-input 
                    placeholder="请输入原密码" 
                    v-model="passForm.oldpw" 
                    show-password
                    @keyup.enter="modifyPassHandler"
                  >
                    <template #prepend>原&emsp;密&emsp;码：</template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="newpw">
                  <el-input 
                    placeholder="请输入新密码" 
                    v-model="passForm.newpw" 
                    show-password
                    @keyup.enter="modifyPassHandler"
                  >
                    <template #prepend>新&emsp;密&emsp;码：</template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="newpw2">
                  <el-input 
                    placeholder="再次输入新密码" 
                    v-model="passForm.newpw2" 
                    show-password
                    @keyup.enter="modifyPassHandler"
                  >
                    <template #prepend>确认新密码：</template>
                  </el-input>
                </el-form-item>
              </el-form>                            
            </div>
            <el-button plain @click="modifyPassHandler">修改</el-button>
          </el-tab-pane>
          <el-tab-pane label="修改头像">
            <div class="updateAvatar">
              <div class="avatarCon">
                <el-upload
                  class="avatar-uploader"
                  :action="baseURL+'/user/avatar'"
                  :show-file-list="false"
                  :with-credentials="true"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-divider direction="vertical"></el-divider>
                <div class="avatarRight">
                  <img class="previewAvatar" :src="`${baseURL}${userInfo.avatar}`" alt="">
                  <p>当前头像</p>
                </div> 
              </div>
              <div class="avatarBottom">
                <p class="avatarTip">点击左侧区域选择图片上传：支持JPG、PNG格式，图片需小于500Kb</p>
                <el-button plain>更新</el-button>
              </div>              
            </div>            
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
  <AppNav />
  <AppFooter />
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import AppNav from '@/components/AppNav'
import AppCover from '@/components/AppCover'
import AppFooter from '@/components/AppFooter'

export default {
  name: 'UserProfile',
  components: { AppNav, AppCover, AppFooter },
  data(){
    return{
      tabPosition: 'left',
      coverURL: '/files/img/section_cover/home.jpg',
      coverPrURL: '/files/img/section_cover/home_pr.jpg',
      oldName: '',
      nameForm:{
        newName: ''
      },
      passForm:{
        oldpw:'',
        newpw:'',
        newpw2:'',
      },     
      imageUrl:'',
      rules:{
        newName: [{
          validator(rule, value, callback) {
            let reg = /^[^\s]{2,8}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error("2-8位非空格字符"))
            }
          },
          trigger: 'blur'
        }],
        oldpw: [{
          validator(rule, value, callback) {
            let reg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error("6-16位字符"))
            }
          },
          trigger: 'blur'
        }],
        newpw: [{
          validator(rule, value, callback) {
            let reg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error("6-16位字符"))
            }
          },
          trigger: 'blur'
        }],
        newpw2: [{
          validator: (rule, value, callback) => {
            if (!value){
              callback(new Error("密码不能为空"))
            }else if (value !== this.passForm.newpw) {
              callback(new Error("两次输入密码不一致"))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  mounted(){
    this.oldName = this.userInfo.user
  },
  methods: {
    ...mapMutations(['updateUserInfo', 'updateUserName']),
    handleAvatarSuccess(res, file){
      if(res.code){
        return this.$message.error(res.msg)
      }
      this.imageUrl = URL.createObjectURL(file.raw);
      // 更新vuex数据
      this.updateUserInfo(res.data)
      //提示成功
      this.$message.success('头像更新成功')
    },
    beforeAvatarUpload(file){
      const fileType = file.type
      const isLt2M = file.size / 1024 < 500
      const isImage = /^image\/(jpeg|png)$/.test(fileType)

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 500Kb!')
      }
      return isImage && isLt2M;
    },   
    // 保存新昵称
    async saveNameHandler(){
      this.$refs.nameForm.validate(async v => {
        if(v){
          let {data} = await this.$axios({
            method: 'post',
            url: '/user/name',
            data: {
              user: this.nameForm.newName
            }
          })

          if(data.code){
            return this.$message.error(data.msg)
          }
          // 修改成功，更新vuex中的userInfo
          this.updateUserName(this.nameForm.newName)
          // 提示成功
          this.$message.success('新用户名保存成功')
          // 清空输入框
          this.$refs.nameForm.resetFields()
        }else{
          return false
        }
      })
      
    },
    //修改密码
    async modifyPassHandler(){
      this.$refs.passForm.validate(async v => {
        if(v){
          let {data} = await this.$axios({
            method: 'post',
            url: 'user/pass',
            data:{
              oldPass: this.passForm.oldpw,
              pass: this.passForm.newpw
            }
          })

          if(data.code){
            return this.$message.error(data.msg)
          }
          // 密码修改成功，清空vuex中的userInfo
          this.updateUserInfo({})
          // 跳转至首页
          this.$router.replace('/')
          // 提示成功
          this.$message.success('密码修改成功')
          // 清空输入框
          this.$refs.passForm.resetFields()
        }else{
          return false
        }
      })
    },
    //处理时间格式
    formatDate(val) {
      let date = new Date(val),
        YY = date.getFullYear(),
        MM = date.getMonth() + 1,
        DD = date.getDate(),
        hh = date.getHours(),
        mm = date.getMinutes(),
        ss = date.getSeconds()

      hh < 10 && (hh = '0' + hh)
      mm < 10 && (mm = '0' + mm)
      ss < 10 && (ss = '0' + ss)

      return `${YY} 年 ${MM} 月 ${DD} 日 ${hh}:${mm}:${ss}`
    }
  },
  created(){    
    if(!this.userInfo.user){
      this.$router.replace('/')
    }
  }
}
</script>

<style lang="less" scoped>
@pageWidth: 48rem;

#UserProfile{
  width: @pageWidth;
  margin: 3rem auto;
  .content{
    .titleTip{
      text-align: left;
      padding: 5px 10px;
      font-size: 1.5rem;
      font-weight: bold;
      color: #555;
      border-left: 4px solid #555;
    }
    .modifyTitle{
      margin-bottom: 20px;
    }
    .userOriginal{
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 10px;
      .img{
        margin: 10px auto 25px;
        width: 100px;
        height: 100px;
        background-size: cover;
        background-position: center;
        border-radius: 50%;
        border: 8px solid #eee;
      }
      .nickName{
        font-size: 1.5rem;
        font-weight: 600;
        padding-bottom: 10px;
      }
      .userRegDate{
        span{
          color: #99a2aa;
        }
      }
    }
    .modifyInfo{
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      .modifyName, .modifyPW{
        /deep/ .el-input-group{
          margin-bottom: 2px;
        }
      }
      .updateAvatar{
        .avatarCon{
          display: flex;
          justify-content: flex-start;
          /deep/ .el-divider--vertical{
            height: 8rem;
            margin: 0 2rem;
          }
          .avatarRight{
            .previewAvatar{
              width: 5rem;
              height: 5rem;
              // margin-top: 2rem;
              border-radius: 50%;
            }
            p{
              font-size: 0.75rem;
              color: #99a2aa;
              margin-top: 10px;
            }
          }
        }
        .avatarBottom{
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          margin-top: 10px;
          .avatarTip{
            font-size: 0.75rem;
            color: #99a2aa;
            padding: 10px 0;
            text-align: left;
          }
        }        
      }
      /deep/ .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        float: left;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 1.5rem;
        color: #8c939d;
        width: 7rem;
        height: 7rem;
        line-height: 7rem;
        text-align: center;
      }
      .avatar {
        width: 7rem;
        height: 7rem;
        display: block;
      }
    }
  }

  /deep/ .el-button{
    float: left;
    color: white;
    font-size: 0.75rem;
    background-color: #34495e;
    border-radius: 4px;
  }
  /deep/ .el-button.is-plain:focus, .el-button.is-plain:hover{
    opacity: 0.8;
    -webkit-transition: all .3s ease-in-out;
    -moz-transition: all .3s ease-in-out;
    transition: all .3s ease-in-out;
    background: #34495e;
    border-color: #34495e;
  }

  /deep/ .el-tabs--left, .el-tabs--right{
    max-height: 300px;
  }

  /deep/ .el-tab-pane{
    margin-left: 10px;
  }
}

/* 很小的设备（手机等，小于 600px） */
@media only screen and (max-width: 600px) { 
  #UserProfile {
    max-width: 100vw;
  }
}

/* 比较小的设备（竖屏的平板，屏幕较大的手机等, 大于 600px） */
@media only screen and (min-width: 600px) { 
  #UserProfile {
    min-width: 34rem;
  }
}

/* 中型大小设备（横屏的平板, 大于 768px） */
@media only screen and (min-width: 768px) { 
  #UserProfile {
    min-width: 38rem
  }
}

/* 大型设备（电脑, 大于 992px） */
@media only screen and (min-width: 992px) { 
  #UserProfile {
    min-width: 44rem;
  }
}

/* 超大型设备（大尺寸电脑屏幕, 大于 1200px） */
@media only screen and (min-width: 1200px) { 
  #UserProfile {
    min-width: 48rem;
  }
}
</style>